/**
 * Created by cchen on 2015/4/30.
 */



var userDevice = mongoose.model('user_device_profile');
/*添加cparams 当URL里有问号添加*/
exports.doParser = function (req, res, next) {

    //'/rest/' + RESTFullServiceVersion + '/users/getHomePage/:token/:deviceId'
    var targetURL = '/rest/' + RESTFullServiceVersion + '/users/homePageFreshNews/';
    var oldURL = '/rest/' + RESTFullServiceVersion + '/users/getHomePage/';
    req.cparams = {}
    var params = {};
    var tempArray = req.url.split('?');
    if (tempArray.length == 2) {
        var parts = tempArray[1].split('&');
        for (var i = 0; i < parts.length; i++) {
            var nv = parts[i].split('=');
            if (!nv[0]) continue;
            params[nv[0]] = nv[1] || true;
        }
        req.cparams = params;
    }

    if (req.url.indexOf(targetURL) !== -1 || req.url.indexOf(oldURL) !== -1) {
        var urlArray = req.url.split('?');
        var parts = urlArray[0].split("/");
        var deviceId = parts[parts.length - 1];
        var token = parts[parts.length - 2];
        var saveCallback = function (err, result) {
            if (err) {
                logger.error('Save user device profile err - url-filter ' + err.message);
            }
        }

        userDevice.findOne({userId: token}, function (err, result) {
            if (result === null) {
                var t = new userDevice();
                t.userId = token;
                t.deviceId = deviceId;
                t.os = params.type;
                t.vName = params.vname;
                t.vCode = params.vcode;
                t.save(saveCallback)
            }
            else if (result) {
                result.userId = token;
                result.deviceId = deviceId;
                result.os = params.type;
                result.vName = params.vname;
                result.vCode = params.vcode;
                result.dateLastModified = new Date();
                result.save(saveCallback)
            }


        })

    }

    next();
};